<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-loading size="24px" vertical v-if="isLoading">加载中...</van-loading>
      <div class="goods">
        <GoodsItem
          id="goodslist"
          v-for="(item, index) in historyData"
          :key="index"
          :url="item.img_url"
          :describe="item.title"
          :price="item.market_price"
          :buy="item.buy"
          @click.native="particulars(item.id)"
        ></GoodsItem>
      </div>
    </van-pull-refresh>

    <van-divider v-if="isLoadDone">已经全部加载</van-divider>
  </div>
</template>

<script>
import { getHistory } from "@/api";
import _ from "lodash";
import GoodsItem from "@/component/GoodsItem";
export default {
  components: {
    GoodsItem,
  },
  data() {
    return {
      page: 1,
      pagesize: 8,
      historyData: [],
      isLoadDone: false,
      isLoading: false,
    };
  },
  methods: {
    particulars(id) {
      this.$router.push("/particulars/" + id);
    },
    async onRefresh() {
      this.isLoading = true;
      this.page = 1;
      this.historyData = [];
      let data = await getHistory({ page: this.page, pagesize: this.pagesize });
      if (data.length > 0) {
        this.isLoading = false;
        this.historyData = data;
      }
    },
    async loadGoodsList() {
      // 加载完成就不再触发滚动事件，不再触发请求
      if (this.isLoadDone) {
        return;
      }
      //滚上去的高度
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      //   网页视口的宽度
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //整个页面的高度
      let pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

      if (Math.ceil(scrollTop) + windowHeight === pageHeight) {
        this.page++;
        let data = await getHistory({ page: this.page, pagesize: this.pagesize });
        // this.isLoadDone = false;
        if (data.length === 0) {
          // 说明数据加载完毕了
          this.isLoadDone = true;
          return;
        }
        this.historyData = [...this.historyData, ...data];
      }
    },
  },
  // 节流
  created() {
    this.throttleLoadGoodsList = _.throttle(this.loadGoodsList, 300);
  },
  async mounted() {
    let data = await getHistory({ page: this.page, pagesize: this.pagesize });
    this.historyData = data;
    // 给窗口绑定滚动事件
    window.addEventListener("scroll", this.throttleLoadGoodsList);
  },
  // eslint-disable-next-line vue/no-deprecated-destroyed-lifecycle
  beforeDestroy() {
    window.removeEventListener("scroll", this.throttleLoadGoodsList);
  },
};
</script>

<style lang="scss" scoped>
.goods {
  display: flex;
  flex-wrap: wrap;
  // justify-content: center;
  padding: 5px;

  #goodslist {
    margin: 5px;
  }
}
</style>
